package com.letoo.sso.dataaccess.dao.cahce.impl;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Repository;

import com.letoo.sso.dataaccess.dao.cahce.UserTokenCacheDAO;

@Repository("userTokenCacheDAO")
public class UserTokenCacheDAOImpl extends BaseCacheDAOImpl implements UserTokenCacheDAO {
    public static String PREFIX_USER_TOKEN = "userAndToken:";

    // 有效期30分钟
    // private static long CAPTCHA_EXPIRE_TIME = 30 * 60;

    @Override
    public boolean setUserToken(final long userId, final String token) {
        boolean result = getRedisTemplate().execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) {
                byte[] key = serialize(PREFIX_USER_TOKEN);
                byte[] field = serialize(userId);
                byte[] value = serialize(token);
                // 存储在Hash集合中
                connection.hSet(key, field, value);
                return true;
            }
        });

        return result;
    }

    @Override
    public boolean deleteByUserId(final long userId) {
        boolean result = getRedisTemplate().execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) {
                byte[] key = serialize(PREFIX_USER_TOKEN);
                byte[] field = serialize(userId);
                // 存储在Hash集合中
                connection.hDel(key, field);
                return true;
            }
        });

        return result;
    }

    @Override
    public String getByUserId(final long userId) {
        String result = getRedisTemplate().execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) {
                byte[] key = serialize(PREFIX_USER_TOKEN);
                byte[] field = serialize(userId);
                // 存储在Hash集合中
                byte[] resByte = connection.hGet(key, field);
                if (resByte == null) {
                    return null;
                }
                return deserialize(String.class, resByte);
            }
        });

        return result;
    }

}
